# 针对性修复脚本 - 精确修复第1849行的语法错误
import os
import re

# 文件路径
original_file = r'd:\未知\yolo_apply\video_processing\video_processor.py'
final_backup = r'd:\未知\yolo_apply\video_processing\video_processor.py.final_backup'
temp_file = r'd:\未知\yolo_apply\video_processing\targeted_fixed.py'

# 确保我们使用最终备份
if os.path.exists(final_backup):
    print(f"Using backup for targeted fix: {final_backup}")
    
    # 使用二进制模式读取文件
    with open(final_backup, 'rb') as f:
        binary_content = f.read()
    
    # 尝试解码为文本
    try:
        text_content = binary_content.decode('utf-8')
    except UnicodeDecodeError:
        text_content = binary_content.decode('latin-1')
    
    # 规范化换行符
    text_content = text_content.replace('\r\n', '\n')
    text_content = text_content.replace('\r', '\n')
    
    # 按行分割
    lines = text_content.split('\n')
    
    # 找到_process_loop函数
    function_start = None
    function_end = None
    
    for i, line in enumerate(lines):
        stripped = line.strip()
        if 'def _process_loop' in stripped and stripped.endswith(':'):
            function_start = i
            # 找到函数的缩进级别
            function_indent = len(line) - len(stripped)
        elif function_start is not None and function_end is None:
            # 检查是否是下一个函数或类定义（表示函数结束）
            if (stripped.startswith('def ') and len(line) - len(stripped) == function_indent) or \
               (stripped.startswith('class ') and len(line) - len(stripped) == function_indent):
                function_end = i
                break
    
    if function_start is not None:
        print(f"Function _process_loop found at line {function_start+1}")
        if function_end is not None:
            print(f"Function ends at line {function_end+1}")
        else:
            print("Function end not found, using end of file")
            function_end = len(lines)
        
        # 重写整个函数，确保正确的缩进和语法
        new_lines = []
        in_function = False
        
        for i, line in enumerate(lines):
            if i == function_start:
                in_function = True
                # 添加函数定义行
                new_lines.append(line)
                continue
            elif i == function_end:
                in_function = False
                new_lines.append(line)
                continue
            
            if in_function:
                # 在函数内，规范化缩进为4个空格
                stripped = line.strip()
                if not stripped or stripped.startswith('#'):
                    # 空行或注释保留
                    if stripped.startswith('#'):
                        new_lines.append(' ' * (function_indent + 4) + stripped)
                    else:
                        new_lines.append('')
                else:
                    # 检查是否包含 'current_time = time.time()' 或类似内容
                    if 'time.time()' in stripped:
                        # 确保这行语法正确
                        new_lines.append(' ' * (function_indent + 4) + 'current_time = time.time()')
                    # 检查是否包含错误率相关的代码
                    elif '错误率过高' in stripped:
                        # 只保留注释行
                        new_lines.append(' ' * (function_indent + 4) + '# 错误率过高时触发警告和恢复')
                    elif 'error_count = 0' in stripped:
                        # 只保留重置错误计数行
                        new_lines.append(' ' * (function_indent + 4) + 'error_count = 0')
                    elif 'max_queue_size' in stripped:
                        # 确保这行语法正确
                        new_lines.append(' ' * (function_indent + 4) + 'max_queue_size = self.config.get(\'max_queue_size\', 50)')
                    else:
                        # 其他行使用正确的缩进
                        new_lines.append(' ' * (function_indent + 4) + stripped)
            else:
                # 不在函数内，保留原行
                new_lines.append(line)
        
        # 将新行列表重新组合为文本
        new_content = '\n'.join(new_lines)
        
        # 写入修复后的文件
        with open(temp_file, 'w', encoding='utf-8') as f:
            f.write(new_content)
        
        print(f"Created targeted fixed file: {temp_file}")
        
        # 替换原文件
        os.replace(temp_file, original_file)
        print(f"Replaced original file with targeted fixed version")
        print("Now let's try to compile again...")
    else:
        print("Error: Could not find _process_loop function in the file")
else:
    print(f"Error: Final backup file not found: {final_backup}")